<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas绘制带箭头的直线</title>
  <style>
    canvas {
      border: 1px solid #000;
    }
  </style>
</head>
<body>

<canvas id="myCanvas" width="500" height="500"></canvas>

<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var isDrawing = false;
  var startX, startY;

  function handleMouseDown(e) {
    isDrawing = true;
    startX = e.clientX - canvas.offsetLeft;
    startY = e.clientY - canvas.offsetTop;
  }

  function handleMouseMove(e) {
    if (!isDrawing) return;

    var currentX = e.clientX - canvas.offsetLeft;
    var currentY = e.clientY - canvas.offsetTop;

    context.clearRect(0, 0, canvas.width, canvas.height);

    drawArrow(startX, startY, currentX, currentY);
  }

  function handleMouseUp() {
    isDrawing = false;
  }

  function drawArrow(startX, startY, endX, endY) {
    var angle = Math.atan2(endY - startY, endX - startX);
    var arrowSize = 10;

    // 绘制直线
    context.beginPath();
    context.moveTo(startX, startY);
    context.lineTo(endX, endY);
    context.stroke();

    // 绘制箭头
    context.beginPath();
    context.moveTo(endX - arrowSize * Math.cos(angle - Math.PI / 6), endY - arrowSize * Math.sin(angle - Math.PI / 6));
    context.lineTo(endX, endY);
    context.lineTo(endX - arrowSize * Math.cos(angle + Math.PI / 6), endY - arrowSize * Math.sin(angle + Math.PI / 6));
    context.closePath();
    context.fill();
  }

  canvas.addEventListener('mousedown', handleMouseDown);
  canvas.addEventListener('mousemove', handleMouseMove);
  canvas.addEventListener('mouseup', handleMouseUp);
</script>

</body>
</html>